# -*- coding: utf-8 -*-

from fire_control_spider.utils import ContentProcessor
from bs4 import BeautifulSoup
from .common import update_media_urls
from ..base_parser import BasePageParser


class PressReleasesParser(BasePageParser):
    """新闻详情页解析器"""
    
    def __init__(self, spider):
        super().__init__(spider)
        self.site_name = 'iaff'
        self.categorys = ['Home', 'Newsroom', 'Press Kit', 'About the IAFF', 'Press Releases']
        
    
    def can_handle(self, response):
        """判断是否为新闻详情页"""
        return response.url == 'https://www.iaff.org/press-releases/'
    
    def parse(self, response):
        """解析新闻详情页"""
        self.logger.info(f"开始处理详情页 {response.url}")

        # 使用BeautifulSoup提取标题
        soup = BeautifulSoup(response.text, 'html.parser')

        rows = soup.select('dl')

        break_flag = 0
        for dl in rows:
            link = dl.select_one('a')
            href = link.get('href')
            if 'pdf' in href:
                yield self.parse_pdf(response, dl)
            else:
                detail_url = self.urljoin(response.url, href)
                yield self.make_request(
                    detail_url,
                    callback=self.spider.parse,  # 返回主spider进行路由
                    meta={
                        'category_url': response.url,
                        'page_type': 'iaff_news_detail',
                        'categorys': self.categorys
                    }
                ) 



    
    def parse_pdf(self, response, dl):
        # 创建基础item
        item = self.create_webpage_item(response)
        item['category'] = self.categorys
        item['title'] = dl.select_one('a').get_text(strip=True)
        href = dl.select_one('a').get('href')
        url = self.urljoin(response.url, href)

        pub_date = dl.select_one("dt span").get_text(strip=True)
        # INSERT_YOUR_CODE
        # pub_date 格式为6/30/25，需转为2025-06-30
        # 先拆分
        try:
            month, day, year = pub_date.split('/')
            # 处理年份为两位数，假设21世纪
            if len(year) == 2:
                year = '20' + year
            item['publish_time'] = f"{year}-{int(month):02d}-{int(day):02d}"
        except Exception as e:
            item['publish_time'] = ''
        item['remark'] = {}
        item['main_body'] = ""
        item['main_files'] = [{'full_url': url, 'name': item['title']}]

        return item

        



